<template>
  <div class="content">
    <el-form ref="ruleFormRef" action="#" v-loading="loading" :model="ruleForm" status-icon :rules="rules" label-width="auto"
      class="demo-ruleForm">
      <el-form-item label="类型" prop="status">
        <el-radio-group v-model="ruleForm.type" size="small" :disabled="disabled">
              <el-radio v-for="item in proxy.$reasonTypeOptions" :value="item.value" size="small">{{ item.label}}</el-radio>
            </el-radio-group>
      </el-form-item>
      <el-form-item label="名称" prop="name">
        <el-input v-model="ruleForm.name" type="text" placeholder="请输入名称" autocomplete="off" :disabled="disabled" />
      </el-form-item>
      
      <el-form-item label="状态" prop="status">
        <el-radio-group v-model="ruleForm.status" size="small" :disabled="disabled">
          <el-radio :value="1" size="small">
            启用
          </el-radio>
          <el-radio :value="2" size="small">禁用</el-radio>
        </el-radio-group>
      </el-form-item>

      <el-form-item label="备注" prop="content">
        <el-input v-model="ruleForm.content" autosize :disabled="disabled" type="textarea" placeholder="请输入内容"
          autocomplete="off" />
      </el-form-item>
      <el-form-item v-if="props.type !== 'info'">
        <el-button size="large" type="primary" @click="submitForm(ruleFormRef)">提交</el-button>
        <el-button size="large" @click="resetForm(ruleFormRef)">重置</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>
<script lang="ts" setup>
import { onMounted, reactive, ref, defineEmits, defineProps,getCurrentInstance } from 'vue'
import type { FormInstance, FormRules } from 'element-plus'
import { reasonApi } from '@/utils/api/reason';
import { ElMessage } from 'element-plus'
const { proxy } = getCurrentInstance(); // 获取当前Vue实例的代理对象，用于访问全局属性。
const props = defineProps({
  id: Number,
  type: String,
  pid: Number,
});
const disabled = ref(false)
if (props.type === 'info') {
  disabled.value = true
}
// 定义自定义事件
const emits = defineEmits(['close-dialog']);
// 使用 useRoute 获取参数
const loading = ref(false)


const convertToTree = (data: any[]): Tree[] => {
  const tree = [];
  const map = {};

  // 第一步：创建一个以 id 为键的映射表
  data.forEach(item => {
    map[item.id] = { ...item, children: [],disabled:(props.id === item.id?true:false)||(props.pid?true:false) };
  });

  // 第二步：找出所有可能的父节点 id
  const allParentIds = new Set(data.map(item => item.pid));

  // 第三步：构建树形结构
  data.forEach(item => {
    if (!map[item.pid]) {
      // 如果该元素的 pid 不在 map 中，说明它没有父级，是根节点
      tree.push(map[item.id]);
    } else {
      // 否则，找到其父节点并将其添加到父节点的 children 数组中
      const parent = map[item.pid];
      if (parent) {
        parent.children.push(map[item.id]);
      }
    }
  });

  return tree;
}

const onImgChange = (file: any) => {
  console.log(file,'监听到')
  ruleForm.avatar = file 
  
}
const getInfo = async (id: string) => {
  // 这里是获取信息的接口
  console.log(id,'jiba')

  loading.value = true
  const res = await reasonApi.info({ id: id })
  res.data.avatar = res.data.avatar?JSON.parse(res.data.avatar):[]
  console.log(res.data,'详情')
  loading.value = false
  Object.assign(ruleForm, res.data)
}

const tableData = ref([
  {
    id: 0,
    name: '一级',
  }
])

const ruleFormRef = ref < FormInstance > ()

interface IForm {
  id: string
  name: string
  status: string
  content: string
}

const ruleForm = reactive < IForm > ({
  id: null,
  name: '',
  status: 1,
  content: '',
})

const rules = reactive < FormRules < typeof ruleForm >> ({
  pid: [{ required: true, message: '请选择上级', trigger: 'blur' }],
  name: [{ required: true, message: '请输入名称', trigger: 'blur' }],
  status: [{ required: true, message: '请选择状态', trigger: 'blur' }],
})


const submitForm = (formEl: FormInstance | undefined) => {
  console.log(ruleForm,'000')

  if (!formEl) return
  formEl.validate((valid) => {
    if (valid) {
      loading.value = true
      if (ruleForm.id == null) {
        reasonApi.create(ruleForm).then((res) => {
          loading.value = false
          if (res.code === 200) {
            emits('close-dialog');
            ElMessage({
              message: res.message,
              type: res.type,
            })
          } else {
            ElMessage({
              message: res.message,
              type: res.type,
            })
          }
        })
      } else {
        reasonApi.update(ruleForm).then((res) => {
          loading.value = false
          if (res.code === 200) {
            emits('close-dialog');
            ElMessage({
              message: res.message,
              type: res.type,
            })
          } else {
            ElMessage({
              message: res.message,
              type: res.type,
            })
          }
        })
      }

    } else {
      loading.value = false

      console.log('error submit!')
    }
  })
}

const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
}

onMounted(() => {
  console.log(props.id, '之心')
  // 获取数据
  if (props.id) {
    getInfo(props.id)
  }

})
</script>

<style scoped>
.demo-ruleForm {
  background: #fff;
  padding: 20px;
  margin-top: 10px;
}
</style>
